#!/usr/bin/env ruby
# -*- ruby -*-

require 'common'
require 'open-uri'

def print_header
  puts 'module Rdio'
  puts ''
  puts '  class Api < BaseApi'
  puts ''
  puts '    def initialize(key,secret)'
  puts '      super key,secret'
  puts '    end'
  puts
end

url = 'http://developer.rdio.com/docs/read/rest/Methods'
method = nil
return_comment = nil
in_return = false
args = []
comment = nil

print_methods = ARGV.index '-m'

if not print_methods
  print_header
end

open(url).read.split(/\n/).each do |line|
  if method
    line.scan /<p>([^<em].*)<\/p>/ do |res|
      if in_return and not return_comment
        return_comment = res[0]

        if print_methods
          call = camel2underscores method
          puts
          puts "    # #{comment}"
          print "    def #{call}("
          print args.map {|a| a[0]}.join(',')
          puts ")"
          print "      return api.#{method} "
          print args.map {|a| a[0]}.join(',')
          puts
          puts "    end"
        else
          puts '  # ' + comment
          print '  def ' + method + '('
          print args.map {|a| a[0]}.join(', ')
          print ')'
          puts
          puts '    method = \'' + method + '\''
          puts '    type = TODO'
          print '    args = {'
          print args.map {|a| "'" + a[0] + "'=>" + a[0]}.join ', '
          print '}'
          puts
          puts '    return_object type,method,args'
          puts '  end'
          puts
        end
        
        method = nil
        args = []
        in_return = false
        return_comment = nil

      elsif method
        comment = res[0]
      end
    end
    line.scan /<dt>(\w+)<\/dt>\s*<dd>(.+)<\/dd>/ do |res|
      arg,descr = res
      args << [arg.strip,descr.strip]
    end
    line.scan /<h3>Returns<\/h3>/ do
      in_return = true
    end
  end
  line.scan />(\w+)<\/h2>/ do |res|
    method = res[0]
    in_return = false
    return_comment = nil
  end
end
